package thread;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wx
 * Date: 2024-02-14
 * Time: 21:53
 */
public class ThreadDemo35 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int result = 0;
                for (int i = 0; i < 1000; i++) {
                    result += i;
                }
                return result;
            }
        };

        // Thread t = new Thread(callable);Thread 没有提供构造函数来传入 callable
        // 引入FutureTask 类,作为 Thread 和 callable "粘合剂"
        FutureTask<Integer> futureTask = new FutureTask<>(callable);
        //未来的任务,还没有执行完,既然未来才执行完毕,最终去取结果的时候,就需要凭据,凭据就是 futureTask
        Thread t = new Thread(futureTask);
        t.start();

        //接下来代码也不需要 join,使用futuretask获取到结果
        System.out.println(futureTask.get());//这个操作带有阻塞功能,等到执行完了,return的结果,就会被返回回来

    }
}
